package o2o.web.actions.user.browse;

import com.jinyou.utils.common.ValidateUtil;
import o2o.cache.shop.ShopMemory;
import o2o.cache.user.UserInfoMemory;
import o2o.config.dao.UserDaoSql;
import o2o.config.dao.utils.DaoUtils;
import o2o.config.dao.utils.Expression;
import o2o.config.dao.utils.QueryCondition;
import o2o.dao.PO.PojoTables;
import o2o.company.model.ShopInfo;
import o2o.dao.PO.user.UserInfo;
import o2o.dao.PO.user.browse.BROWSE_HISTORY_TYPE;
import o2o.dao.PO.user.browse.UserBrowseHistory;
import o2o.system.data.SYS_SETTINGS;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.sql.SQLException;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * @Classname UserBrowseHistoryMan
 * @Description TODO
 * @Date 2019/4/27 11:39
 * @Created by yangtk
 */
@Component
public class UserBrowseHistoryService {

    // username
    private static ConcurrentHashMap<Long, Set<UserBrowseHistory>> dataMap = new ConcurrentHashMap<>();

    // 添加
    @Async
    public void addOrUpdateBrowseHistory(String username, Long shopId, Long goodsId, Integer type) {
        // 是否插入
        if (SYS_SETTINGS.HAS_BROWSE_HISTORY != null && SYS_SETTINGS.HAS_BROWSE_HISTORY == 1) {
            if (ValidateUtil.isNull(username) || ValidateUtil.isNotID(shopId)) {
                return;
            }
            // 用户
            UserInfo info = UserInfoMemory.getInstance().getUserInfo(username);
            if (info == null) {
                return;
            }
            Long userId = info.getId();
            ShopInfo shopInfo = ShopMemory.getInstance().getShopById(shopId);
            if (shopInfo == null) {
                return;
            }
            // 自己访问自己的不要
            if (ValidateUtil.isNotNull(shopInfo.getOwnName()) && ValidateUtil.isNotNull(info.getUsername()) && info.getUsername().equals(shopInfo.getOwnUsername())) {
                return;
            }
            if (type == null) {
                type = BROWSE_HISTORY_TYPE.BROWSE_HISTORY_TYPE_SHOP;
            }
            UserBrowseHistory userBrowseHistory = null;
            Set<UserBrowseHistory> histories = dataMap.get(userId);
            if (histories == null || histories.isEmpty()) {
                histories = this.queryByUserId(userId);
            }
            if (histories != null && histories.size() > 0) {
                for (UserBrowseHistory u : histories) {
                    if (type.equals(BROWSE_HISTORY_TYPE.BROWSE_HISTORY_TYPE_SHOP) && u.getShopId() != null && u.getShopId() - shopId == 0) {
                        userBrowseHistory = u;
                        break;
                    } else if (type.equals(BROWSE_HISTORY_TYPE.BROWSE_HISTORY_TYPE_GOODS) && ValidateUtil.isID(goodsId) && u.getGoodsId() != null && u.getGoodsId() - goodsId == 0) {
                        userBrowseHistory = u;
                        break;
                    }
                }
            } else {
                histories = new HashSet<>();
            }
            if (userBrowseHistory != null) {
                StringBuilder updateSql = new StringBuilder();
                updateSql.append("update ").append(PojoTables.USER_BROWSE_HISTORY).append(" set updateUser ='")
                        .append(ValidateUtil.isNull(username) ? "" : username).append("' where delFlag = 0 and userId =")
                        .append(userId).append(" and shopId=").append(shopId).append(" and type ='").append(type).append("'");
                if (ValidateUtil.isID(goodsId)) {
                    updateSql.append(" and goodsId = ").append(goodsId);
                }
                try {
                    UserDaoSql.getInstance().executeBySql(updateSql.toString());
                    histories.add(userBrowseHistory);
                    dataMap.put(userId, histories);
                } catch (Exception e) {
                    System.out.println("浏览数据更新异常");
                    e.printStackTrace();
                }
            } else {
                userBrowseHistory = new UserBrowseHistory(type, userId, shopId, goodsId == null ? 0 : goodsId, username);
                boolean isInsertOk = true;
                Long id = null;
                try {
                    id = UserDaoSql.getInstance().saveObj(PojoTables.USER_BROWSE_HISTORY, userBrowseHistory);
                } catch (Exception e) {
//                    e.printStackTrace();
                    System.out.println("插入浏览异常,无需处理");
                    isInsertOk = false;
                }
                if (!isInsertOk) {
                    //更新
                    StringBuilder updateSql = new StringBuilder();
                    updateSql.append("update ").append(PojoTables.USER_BROWSE_HISTORY).append(" set updateUser ='")
                            .append(ValidateUtil.isNull(username) ? "" : username).append("' where delFlag = 0 and userId =")
                            .append(userId).append(" and shopId=").append(shopId).append(" and type ='").append(type).append("'");
                    if (ValidateUtil.isID(goodsId)) {
                        updateSql.append(" and goodsId = ").append(goodsId);
                    }
                    try {
                        UserDaoSql.getInstance().executeBySql(updateSql.toString());
                        histories.add(userBrowseHistory);
                        dataMap.put(userId, histories);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    userBrowseHistory.setId(id);
                    histories.add(userBrowseHistory);
                    dataMap.put(userId, histories);
                }
            }
        }
    }

    private Set<UserBrowseHistory> queryByUserId(Long userId) {
        QueryCondition query = QueryCondition.getInstance();
        Expression expression = Expression.getInstance();
        expression.addChild("delFlag", 0);
        expression.addChild("userId", userId);
        query.addCondition(expression);

        String sql = DaoUtils.getSql(PojoTables.USER_BROWSE_HISTORY, query);
        List<UserBrowseHistory> list = null;
        try {
            list = (List<UserBrowseHistory>) UserDaoSql.getInstance().list(UserBrowseHistory.class, sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if (ValidateUtil.isAbsList(list)) {
            return list.stream().collect(Collectors.toSet());
        }
        return Collections.emptySet();
    }

    // 清除缓存
    public void cleanCache(Long userId) {
        if (ValidateUtil.isID(userId)) {
            dataMap.remove(userId);
        }
    }

}
